"""
squared_hinge
"""
import numpy as np
from keras.losses import SquaredHinge, squared_hinge


def get_data():
    """

    :return:
    """
    y_true = [[0., 1.], [0., 0.]]
    y_pred = [[0.6, 0.4], [0.4, 0.6]]

    return np.array(y_true), np.array(y_pred)


def compute_squared_hinge(y_true, y_pred):
    """

    :param y_true:
    :param y_pred:
    :return:
    """
    # 将true中的0置换为-1
    y_true[y_true == 0] = -1
    loss = np.maximum(1 - y_true * y_pred, 0)

    return np.power(loss, 2).mean(axis=1), np.power(loss, 2).mean()


def run():
    """
    主程序
    :return:
    """
    y_true, y_pred = get_data()

    # 自己计算
    my_loss_1, my_loss_2 = compute_squared_hinge(y_true=y_true, y_pred=y_pred)

    sh = SquaredHinge()
    class_loss = sh(y_true=y_true, y_pred=y_pred)

    function_loss = squared_hinge(y_true=y_true, y_pred=y_pred)

    info = 'Class: my: {}, keras: {}\nFunction: my: {}, keras: {}'.\
        format(my_loss_2, class_loss, my_loss_1, function_loss)

    print(info)


if __name__ == '__main__':
    run()
